<?php
namespace App\Console\Commands;

use Illuminate\Console\Command;

//ini_set('date.timezone','Asia/Shanghai');
class SendMail extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'SendMail';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'tick send mail';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        \Log::info('crontab:SendMail'.' START', []);

        $valid_time = date("Y-m-d H:i:s");
        $list = \DB::connection('mysql')->table('email')->select('id', 'end_time', 'area_list')->where('send_time', 0)->where('end_time', '<', $valid_time)->get();

        $url = env('APP_URL'). "/admin/mail/api-send";

        \Log::info('crontab:SendMail'. ' count = '. $list->count() );
        $log_ids = '';
        // /admin/mail/api-send?id=143&status=1
        foreach ($list as $obj) {

            $this->curl_request($url, ['id' => $obj->id, 'status' => 1]);
            $log_ids .='|'. $obj->id;
        }
        \Log::info('crontab:SendMail'. ' END', [$log_ids]);
        exit;
    }

    /** 
     * 执行一个 HTTP 请求
     *
     * @param string    $Url    执行请求的Url
     * @param mixed $Params 表单参数
     * @param string    $Method 请求方法 post / get
     * @return array 结果数组
     */
    public function curl_request($Url, $Params, $Method='post'){

        $Params =  http_build_query($Params , '' , '&');
        $Curl = curl_init();//初始化curl

        if ('get' == $Method){//以GET方式发送请求
            curl_setopt($Curl, CURLOPT_URL, "$Url?$Params");
        }else{//以POST方式发送请求
            curl_setopt($Curl, CURLOPT_URL, $Url);
            curl_setopt($Curl, CURLOPT_POST, 1);//post提交方式
            curl_setopt($Curl, CURLOPT_POSTFIELDS, $Params);//设置传送的参数
        }   

        curl_setopt($Curl, CURLOPT_HEADER, false);//设置header
        curl_setopt($Curl, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
        curl_setopt($Curl, CURLOPT_CONNECTTIMEOUT, 3);//设置等待时间

        $Res = curl_exec($Curl);//运行curl
        $Err = curl_error($Curl);

        if (false === $Res || !empty($Err)){
            $Errno = curl_errno($Curl);
            $Info = curl_getinfo($Curl);
            curl_close($Curl);

            return array(
                'result' => false,
                'errno' => $Errno,
                'msg' => $Err,
                'info' => $Info,
            );  
        }   
        curl_close($Curl);//关闭curl
        \Log::debug('crontab:SendMail', [$Url, $Params, $Res]);
        return array(
            'result' => true,
            'msg' => $Res,
        );  
    
    } 

}
